useRef ref callback


Posted by mijouhsieh on 2023-12-27

React官方 Manipulating the DOM with Refs

Getting a ref to the node 取得DOM node的ref物件

4 steps

三種寫法 使用useRef

第一種: 呼叫3次useRef 3個event handler
第二種 sandcodebox: 3張圖放在itemsRef中,只呼叫一次useRef。
每張圖片 ref物件用ref callback操作,map方法<img> set()新增元素,delete()刪除元素
???map物件只存一個圖片元素嗎?
<button> has()確認map物件中是否有此元素,回傳boolean。有元素的話,使用get()將此元素回傳,再用browser API scrollIntoView()將圖片滾動效果。

第三種: 重複出現的callback函式宣告成函式,重複使用
<img> ref屬性的ref callback,重複三次出現,宣告成 refCallback函式。在每個rel屬性中呼叫函式,並帶入map中的key。 rel={refCallback("鍵")}

<button> onClick事件執行的event handler,重複三次出現,宣告成handleClick。
‵<button onClick={handleClick("Tom"}>`


#React Hook #useRef #Map object #callback function







Related Posts

DAY14:Quarter of the year

DAY14:Quarter of the year

ASP.NET Core Web API 入門教學 - 使用PUT更新資料

ASP.NET Core Web API 入門教學 - 使用PUT更新資料

NPM & Node.js & Package.json的關係與使用

NPM & Node.js & Package.json的關係與使用


Comments